import subprocess
import pandas as pd
import os
from read_xlsx_sheet1 import read_execle,Coating_Name,Coating_Name_row_element
import re

# 读取Excel文件
                                            #这个路径也得换-------------
# file ='C:\\Users\\admin\\Desktop\\01 Adjust&Data\\B\\B-Simulation-Setting.xlsx'
# PL_path = 'C:/Users/admin/Desktop/03_simulation_example/00 Structure/00 NK/'
# new_par='new_G_C9.par'




#比较前三个单词
def compare_first_three_words(str1, str2):
    # 分割字符串为单词列表
    words1 = str1.split()
    words2 = str2.split()
    
    # 获取前三个单词
    first_three_words1 = words1[:3]
    first_three_words2 = words2[:3]
    
    # 比较这两个列表的前三个单词是否相等
    return first_three_words1 == first_three_words2



def update_par_file(main_file,out_file,old_line,new_line):
    # modify the new par file
    StartPar = open(main_file,"r")
    StartPar_text = StartPar.read()
    # create new par file name
    NewPar_filename = out_file
    NewPar=open(NewPar_filename,"w")
    # replace lines in base parfile
    Old_lines=old_line # Finds this line in the "main_file" to be modified
    New_lines=new_line # Replaces this line in the updated par file
    NewPar_text=StartPar_text.replace(Old_lines,New_lines)
    # write and close new par file
    NewPar.write(NewPar_text)
    NewPar.close()




#setting_file：需求表格路径
def many_file_sheet1(new_par,setting_file,PL_path):
    list1 = Coating_Name(setting_file,1)
    list2 = Coating_Name_row_element(setting_file,1)
    dict_coatingname = {}

    dcit_name={}
    
    with open(new_par, "r") as StartPar:
        lines=StartPar.readlines()

    list3=[]#存放['SION-1.64-C', 'DOT-80-C-nk_IL1']
    list4=[]#存放新的行
    list5=[]#存放旧的行
    # print(list1)
    # print(len(list1))
    for i in range(0, len(list1)):
        for j in range(0, len(list2)):
            result = read_execle(setting_file, list1[i], list2[j],1)
            dict_coatingname[list2[j]] = result

        refractive_index_curve = dict_coatingname.get('折射率曲线')
        # list3=refractive_index_curve.split()

        if ' ' in str(refractive_index_curve): 
            list3=str(refractive_index_curve).split()#['SION-1.64-C', 'DOT-80-C-nk_IL1']
            print(list3)
            dcit_name[dict_coatingname.get('膜层名称')]=list3
            #拼接新的字符串
            # print(len(list3))
            for k in range(len(list3)):
                coating_name = dict_coatingname.get('膜层名称')
                # print(coating_name)
                thickness = dict_coatingname.get('厚度')
                unit = dict_coatingname.get('单位')
                coating_property = dict_coatingname.get('膜层特性')

                is_disabled = dict_coatingname.get('是否勾选')
                layer_str = f"Layer " + (f"{is_disabled} " if is_disabled else "") + coating_name

                # if thickness and unit:
                layer_str += f" {thickness} {unit} n "

                layer_str += f'File "{PL_path}/{list3[k]}.txt"'
                # print(layer_str)

                if coating_property:
                    layer_str += f" {coating_property}"
                list4.append(layer_str)



            #旧的行
            # j=0
            # for line in lines:
            #     if "Layer" in line and f"{list1[i]}" in line:
            #         list5.append(line.strip())
            #         print('*****')
            #         print(line)
            extracting = False
            for line in lines:
                if "Structure" in line:
                    extracting = True  # 开始提取
                    continue
                if extracting:
                    if "Define" in line:
                        break  # 遇到 "Define" 停止提取
                    if "Layer" in line and f"{list1[i]}" in line:
                        list5.append(line.strip())
                        # print(line)
    #sheet1文件部分 替换成功
    # print(dcit_name)
    # count1=0
    # for item5 in list5:
    #     for item4 in list4:
    #         if compare_first_three_words(item5,item4):
    #             base_name = new_par.rsplit('.', 1)[0]
    #             new_sim_name = f"./first_par_result/{count1}{base_name}"+".par" 
    #             count1=count1+1
    #             update_par_file(new_par,new_sim_name,item5,item4)
        
    
    return list5,list4



def many_file_sheet1_2(list5,list4,new_par,setting_file):
    count3=0
    count4=0#统计有多少个‘折射率曲线‘包含多文件
    list6=[]
    list7=[]
    list8=[]
    list8.append(new_par)
    list11 = Coating_Name(setting_file,1)
    list21 = Coating_Name_row_element(setting_file,1)
    dict_coatingname1 = {}
    for i in range(0, len(list11)):
        for j in range(0, len(list21)):
            result = read_execle(setting_file, list11[i], list21[j],1)
            dict_coatingname1[list21[j]] = result
        refractive_index_curve = dict_coatingname1.get('折射率曲线')
            # list3=refractive_index_curve.split()
        if ' ' in str(refractive_index_curve): 
            count4=count4+1
            if list6==[]:
                count1=1
                string = list5[count3]
                for item4 in list4:
                    # print(item4)
                    if compare_first_three_words(string,item4):
                        base_name = new_par.rsplit('.', 1)[0]
                        new_sim_name = f"{count1}_{base_name}"+".par" 
                        count1=count1+1
                        update_par_file(new_par,f'./first_par_result/{new_sim_name}',string,item4)
                        list6.append(new_sim_name)
            else:
                list7=[]
                string1 = list5[count3]    
                for new_name in list6:
                    count2=1
                    for item4 in list4:
                        # print(item4)
                        if compare_first_three_words(string1,item4):
                            base_name = new_name.rsplit('.', 1)[0]
                            new_name_with_count = re.sub('(\d+)', lambda match: match.group(1) + str(count2), base_name)
                            # new_sim_name = f"{count2}{base_name}"+".par" 
                            new_sim_name = new_name_with_count+".par" 
                            
                            count2=count2+1
                            update_par_file(f'./first_par_result/{new_name}',f'./first_par_result/{new_sim_name}',string1,item4)
                            # print(new_sim_name)
                            list7.append(new_sim_name)
                list6=list7


            # print()
            count3+=1
            # print(count3)
    # print(list6)
    if count4==0:
        # print(f"new_par={new_par}")
        return list8
    if count4==1:
        return list6
    if count4>1:
        return list7
    # return list7




#sheet2文件部分 替换成功
def many_file_sheet2_first(new_par,setting_file,PL_path,a):
    
    list5,list4=many_file_sheet1(new_par,setting_file,PL_path)
    list7=many_file_sheet1_2(list5,list4,new_par,setting_file)
    with open(new_par, "r") as StartPar:
        lines=StartPar.readlines()
    list6=[]#['DOT-130-C-nk_IL2', 'PAS_DLX-100_G6-DOT']
    Gui_Par_Name=[]
    sheet_name = f'Sheet{a}'
    df = pd.read_excel(setting_file, sheet_name=sheet_name,engine='openpyxl')
    count2=0
    
    for index, row in df.iterrows():
        # 检查这一行是否包含"发光光谱"
        if any("发光光谱" in str(value) for value in row):
            # 假设你想检查的是同一行的下一个单元格
            next_cell_value = row.iloc[1]  # 根据实际情况调整索引

            list6=str(next_cell_value).split()
            print(list6)

            if ' ' in str(next_cell_value):
            
                for line in lines:
                    if 'File' in line and 'Power' in line and str(next_cell_value).split()[0] in line:
                        
                        for item6 in list6:
                            new_string=f'File "{PL_path}/{item6}.txt" Power\n'
                            # f'File "{PL_path}{list3[k]}.txt"'
                            # new_sim_name = "emitter_"+f"simulation_copy_5.2_{count2}"+".par" 
                            count2=count2+1

                            for item in list7:
                                base_name = item.rsplit('.', 1)[0]
                                old_name=f'./first_par_result/{base_name}.par'
                                # print(old_name)
                                base_name2 = item.rsplit('.', 1)[0]
                                # print(base_name2)
                                new_name=f"./two_par_result/"+f"{count2}{base_name2}"+".par"
                                new_name2=f"{count2}{base_name2}"+".par"
                                Gui_Par_Name.append(new_name2)
                                # print(new_name)
                                update_par_file(old_name, new_name,line,new_string)
    return Gui_Par_Name



def many_file_sheet2(new_par,setting_file,PL_path,a):
    
    list5,list4=many_file_sheet1(new_par,setting_file,PL_path)
    list7=many_file_sheet1_2(list5,list4,new_par,setting_file)
    # print(f'list7={list7}')
    with open(new_par, "r") as StartPar:
        lines=StartPar.readlines()
    list6=[]#['DOT-130-C-nk_IL2', 'PAS_DLX-100_G6-DOT']
    # Gui_Par_Name=[]
    flag=1
    sheet_name = f'Sheet{a}'
    df = pd.read_excel(setting_file, sheet_name=sheet_name,engine='openpyxl')
    count2=0
    
    for index, row in df.iterrows():
        Gui_Par_Name=[]
        # 检查这一行是否包含"发光光谱"
        if any("发光光谱" in str(value) for value in row):
            # 假设你想检查的是同一行的下一个单元格
            next_cell_value = row.iloc[1]  # 根据实际情况调整索引

            list6=str(next_cell_value).split()
            print(list6)

            if ' ' in str(next_cell_value):
                
            
                for line in lines:
                    # if 'File' in line and 'Power' in line and str(next_cell_value).split()[0] in line:
                    if 'File' in line and ('Power' in line or 'Probability' in line) and str(next_cell_value).split()[0] in line:
                        
                        for item6 in list6:
                            # print(item6)
                            new_string=f'File "{PL_path}/{item6}.txt" {row.iloc[2]}\n'
                            # f'File "{PL_path}{list3[k]}.txt"'
                            # new_sim_name = "emitter_"+f"simulation_copy_5.2_{count2}"+".par" 
                            count2=count2+1

                            for item in list7:
                                base_name = item.rsplit('.', 1)[0]
                                # print(f'flag={flag}')
                                if flag==1:
                                    # print(len(os.listdir('./first_par_result')))
                                    if len(os.listdir('./first_par_result'))==0:
                                        old_name=f'./{base_name}.par'
                                    else:
                                        old_name=f'./first_par_result/{base_name}.par'
                                else:
                                    old_name=f'./two_par_result/{base_name}.par'
                                # print(old_name
                                # print(base_name2)
                                
                                # new_name=f"./two_par_result/"+f"{count2}{base_name}_Ref"+".par"
                                # new_name2=f"{count2}{base_name}_Ref"+".par"
                                new_name_with_count = re.sub('(\d+)', lambda match: match.group(1) + str(count2), base_name)
                                # print(new_name_with_count)

                                # new_name=f"./two_par_result/"+f"{count2}{base_name}"+".par"
                                new_name=f"./two_par_result/"+new_name_with_count+".par"
                                # new_name2=f"{count2}{base_name}"+".par"
                                new_name2=new_name_with_count+".par"
                                Gui_Par_Name.append(new_name2)
                                # print(new_name)
                                # print(f'old_name={old_name}')
                                update_par_file(old_name, new_name,line,new_string)
                        count2=0#重置下表
                        flag+=1
            else:
                if len(os.listdir('./first_par_result'))==0:
                    Gui_Par_Name.append(new_par)
                else:
                    Gui_Par_Name=list7

                
            list7=Gui_Par_Name
    # print(list7)
                            
    return list7